<template>
  <div class="product-list">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" inline>
        <el-form-item label="产品名称" prop="name">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入产品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="产品类型" prop="type">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择产品类型"
            clearable
            style="width: 120px"
          >
            <el-option label="个人贷款" value="personal" />
            <el-option label="企业贷款" value="business" />
            <el-option label="消费贷款" value="consumer" />
            <el-option label="抵押贷款" value="mortgage" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="上架中" value="active" />
            <el-option label="已下架" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="产品名称" min-width="150" />
        <el-table-column prop="type" label="产品类型" width="100">
          <template #default="scope">
            <el-tag :type="getProductTypeTag(scope.row.type)">
              {{ getProductTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="所属分类" width="120" />
        <el-table-column label="贷款金额" width="150">
          <template #default="scope">
            <template v-if="scope.row.loanAmount">
              {{ scope.row.loanAmount.min }}-{{ scope.row.loanAmount.max }}万
            </template>
            <template v-else>--</template>
          </template>
        </el-table-column>
        <el-table-column label="贷款期限" width="150">
          <template #default="scope">
            <template v-if="scope.row.loanTerm">
              {{ scope.row.loanTerm.min }}-{{ scope.row.loanTerm.max }}个月
            </template>
            <template v-else>--</template>
          </template>
        </el-table-column>
        <el-table-column prop="interestRate" label="利率(%)" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '上架中' : '已下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button
                link
                type="primary"
                @click="handleView(scope.row)"
              >查看</el-button>
              <el-button
                link
                type="primary"
                @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                link
                type="primary"
                @click="handleChangeStatus(scope.row)"
              >{{ scope.row.status === 'active' ? '下架' : '上架' }}</el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="650px"
      destroy-on-close
      @closed="resetForm"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
      >
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择产品类型" style="width: 100%">
            <el-option label="个人贷款" value="personal" />
            <el-option label="企业贷款" value="business" />
            <el-option label="消费贷款" value="consumer" />
            <el-option label="抵押贷款" value="mortgage" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="formData.categoryId" placeholder="请选择所属分类" style="width: 100%">
            <el-option 
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="贷款金额" required>
          <el-row :gutter="10">
            <el-col :span="11">
              <el-form-item prop="loanAmount.min">
                <el-input-number
                  v-model="formData.loanAmount.min"
                  :min="0.1"
                  :precision="1"
                  :step="0.1"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">
              <span class="text-gray-500">至</span>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="loanAmount.max">
                <el-input-number
                  v-model="formData.loanAmount.max"
                  :min="formData.loanAmount.min"
                  :precision="1"
                  :step="0.1"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="贷款期限(月)" required>
          <el-row :gutter="10">
            <el-col :span="11">
              <el-form-item prop="loanTerm.min">
                <el-input-number
                  v-model="formData.loanTerm.min"
                  :min="1"
                  :max="formData.loanTerm.max"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">
              <span class="text-gray-500">至</span>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="loanTerm.max">
                <el-input-number
                  v-model="formData.loanTerm.max"
                  :min="formData.loanTerm.min"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="年化利率(%)" prop="interestRate">
          <el-input-number
            v-model="formData.interestRate"
            :min="0"
            :max="100"
            :precision="2"
            :step="0.01"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="还款方式" prop="repaymentMethod">
          <el-select v-model="formData.repaymentMethod" placeholder="请选择还款方式" style="width: 100%">
            <el-option label="等额本息" value="equal_principal_interest" />
            <el-option label="等额本金" value="equal_principal" />
            <el-option label="到期还本付息" value="interest_only" />
            <el-option label="按月付息到期还本" value="monthly_interest" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请条件" prop="applyCondition">
          <el-input
            v-model="formData.applyCondition"
            type="textarea"
            :rows="2"
            placeholder="请输入申请条件"
          />
        </el-form-item>
        <el-form-item label="所需材料" prop="requiredMaterials">
          <el-input
            v-model="formData.requiredMaterials"
            type="textarea"
            :rows="2"
            placeholder="请输入所需材料"
          />
        </el-form-item>
        <el-form-item label="产品说明" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入产品说明"
          />
        </el-form-item>
        
        <!-- 添加产品特性部分 -->
        <el-divider content-position="center">产品特性</el-divider>
        
        <div v-for="(feature, index) in formData.features" :key="index" class="feature-item">
          <el-row :gutter="10">
            <el-col :span="5">
              <el-form-item :label="index === 0 ? '特性键值' : ''" :prop="`features.${index}.key`" :rules="{ required: true, message: '请输入特性键值', trigger: 'blur' }">
                <el-input v-model="feature.key" placeholder="键值" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="index === 0 ? '特性名称' : ''" :prop="`features.${index}.name`" :rules="{ required: true, message: '请输入特性名称', trigger: 'blur' }">
                <el-input v-model="feature.name" placeholder="名称" />
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item :label="index === 0 ? '特性值' : ''" :prop="`features.${index}.value`" :rules="{ required: true, message: '请输入特性值', trigger: 'blur' }">
                <el-input v-model="feature.value" placeholder="值" />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="flex items-center">
              <el-button 
                type="danger" 
                circle
                @click="removeFeature(index)"
                icon="Delete"
                class="mt-1"
              />
            </el-col>
          </el-row>
        </div>
        
        <div class="text-center mb-4">
          <el-button type="primary" @click="addFeature" icon="Plus">添加产品特性</el-button>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="产品详情"
      width="700px"
      destroy-on-close
    >
      <div v-loading="detailLoading" style="min-height: 200px;">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="产品名称">{{ productDetail.name || '--' }}</el-descriptions-item>
          <el-descriptions-item label="产品类型">
            <template v-if="productDetail.type">
              <el-tag :type="getProductTypeTag(productDetail.type)">
                {{ getProductTypeName(productDetail.type) }}
              </el-tag>
            </template>
            <template v-else>--</template>
          </el-descriptions-item>
          <el-descriptions-item label="所属分类">{{ productDetail.categoryName || '--' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <template v-if="productDetail.status">
              <el-tag :type="productDetail.status === 'active' ? 'success' : 'info'">
                {{ productDetail.status === 'active' ? '上架中' : '已下架' }}
              </el-tag>
            </template>
            <template v-else>--</template>
          </el-descriptions-item>
          <el-descriptions-item label="贷款金额">
            <template v-if="productDetail.loanAmount">
              {{ productDetail.loanAmount.min }}-{{ productDetail.loanAmount.max }}万
            </template>
            <template v-else>--</template>
          </el-descriptions-item>
          <el-descriptions-item label="贷款期限">
            <template v-if="productDetail.loanTerm">
              {{ productDetail.loanTerm.min }}-{{ productDetail.loanTerm.max }}个月
            </template>
            <template v-else>--</template>
          </el-descriptions-item>
          <el-descriptions-item label="年化利率">{{ productDetail.interestRate ? `${productDetail.interestRate}%` : '--' }}</el-descriptions-item>
          <el-descriptions-item label="还款方式">{{ productDetail.repaymentMethod ? getRepaymentMethodName(productDetail.repaymentMethod) : '--' }}</el-descriptions-item>
          <el-descriptions-item label="申请条件" :span="2">{{ productDetail.applyCondition || '--' }}</el-descriptions-item>
          <el-descriptions-item label="所需材料" :span="2">{{ productDetail.requiredMaterials || '--' }}</el-descriptions-item>
          <el-descriptions-item label="产品说明" :span="2">{{ productDetail.description || '--' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ productDetail.createTime || '--' }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ productDetail.updateTime || '--' }}</el-descriptions-item>
        </el-descriptions>
        
        <template v-if="productDetail.features && productDetail.features.length > 0">
          <div class="mt-4">
            <h4 class="mb-2">产品特点</h4>
            <el-card v-for="(feature, index) in productDetail.features" :key="index" class="mb-2">
              <div class="font-bold">{{ feature.name }}</div>
              <div>{{ feature.value }}</div>
            </el-card>
          </div>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { productApi, categoryApi } from '@/api/product'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})

// 表格数据
const loading = ref(false)
const total = ref(0)
const tableData = ref([])

// 表单数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const submitLoading = ref(false)
const formData = reactive({
  name: '',
  type: '',
  categoryId: undefined,
  interestRate: 4.35,
  loanAmount: {
    min: 1,
    max: 50
  },
  loanTerm: {
    min: 3,
    max: 36
  },
  repaymentMethod: 'equal_principal_interest',
  applyCondition: '',
  requiredMaterials: '',
  description: '',
  features: []
})

// 详情数据
const detailVisible = ref(false)
const detailLoading = ref(false)
const productDetail = ref({})

// 分类选项
const categoryOptions = ref([])

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入产品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择产品类型', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择所属分类', trigger: 'change' }
  ],
  interestRate: [
    { required: true, message: '请输入年化利率', trigger: 'blur' }
  ],
  'loanAmount.min': [
    { required: true, message: '请输入最小贷款金额', trigger: 'blur' }
  ],
  'loanAmount.max': [
    { required: true, message: '请输入最大贷款金额', trigger: 'blur' }
  ],
  'loanTerm.min': [
    { required: true, message: '请输入最短贷款期限', trigger: 'blur' }
  ],
  'loanTerm.max': [
    { required: true, message: '请输入最长贷款期限', trigger: 'blur' }
  ],
  repaymentMethod: [
    { required: true, message: '请选择还款方式', trigger: 'change' }
  ]
}

// 产品类型标签
const getProductTypeTag = (type) => {
  const map = {
    personal: '',
    business: 'success',
    consumer: 'warning',
    mortgage: 'danger'
  }
  return map[type] || 'info'
}

// 产品类型名称
const getProductTypeName = (type) => {
  const map = {
    personal: '个人贷款',
    business: '企业贷款',
    consumer: '消费贷款',
    mortgage: '抵押贷款'
  }
  return map[type] || type
}

// 还款方式名称
const getRepaymentMethodName = (method) => {
  const map = {
    equal_principal_interest: '等额本息',
    equal_principal: '等额本金',
    interest_only: '到期还本付息',
    monthly_interest: '按月付息到期还本'
  }
  return map[method] || method
}

// 获取产品列表
const getProductList = async () => {
  loading.value = true
  try {
    const res = await productApi.getList(searchForm)
    console.log('产品列表接口返回:', res) // 调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 处理可能的嵌套数据结构
      if (res.data && res.data.rows) {
        // 原始结构: res.data.rows
        tableData.value = res.data.rows
        total.value = res.data.total
      } else if (res.data && res.data.data && res.data.data.rows) {
        // 嵌套结构: res.data.data.rows
        tableData.value = res.data.data.rows
        total.value = res.data.data.total
      } else if (res.data && res.data.code && res.data.data && res.data.data.rows) {
        // 新的嵌套结构: res.data.data.rows, 其中 res.data 包含 code, msg 和 data
        tableData.value = res.data.data.rows
        total.value = res.data.data.total
      } else {
        // 直接是数组的情况
        tableData.value = Array.isArray(res.data) ? res.data : []
        total.value = Array.isArray(res.data) ? res.data.length : 0
        console.warn('产品列表数据结构与预期不符，尝试兼容处理', res.data)
      }
    } else {
      ElMessage.error(res.msg || '获取产品列表失败')
    }
  } catch (error) {
    console.error('获取产品列表出错', error)
    ElMessage.error('获取产品列表出错')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategoryList = async () => {
  try {
    const res = await categoryApi.getList({ status: '1' })
    console.log('分类接口返回数据:', res) // 调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 将树形结构转换为扁平结构的选项
      const options = []
      const flattenCategories = (categories, prefix = '') => {
        if (!Array.isArray(categories)) {
          console.error('分类数据不是数组类型', categories)
          return
        }
        
        categories.forEach(category => {
          options.push({
            id: category.id,
            name: prefix + category.name
          })
          if (category.children && category.children.length > 0) {
            flattenCategories(category.children, prefix + category.name + ' / ')
          }
        })
      }
      
      // 处理嵌套的数据结构，尝试所有可能的路径
      let categoryData = null
      if (res.data && Array.isArray(res.data)) {
        categoryData = res.data
      } else if (res.data && res.data.data && Array.isArray(res.data.data)) {
        categoryData = res.data.data
      } else if (res.data && res.data.rows && Array.isArray(res.data.rows)) {
        categoryData = res.data.rows
      } else if (res.data && res.data.code && res.data.data && Array.isArray(res.data.data.rows)) {
        // 新的嵌套结构：res.data 包含 code、msg 和 data，data.rows 是分类数组
        categoryData = res.data.data.rows
      } else if (res.data && res.data.code && res.data.data && Array.isArray(res.data.data)) {
        // 新的嵌套结构：res.data 包含 code、msg 和 data，data 是分类数组
        categoryData = res.data.data
      }
      
      if (categoryData) {
        flattenCategories(categoryData)
        categoryOptions.value = options
        console.log('处理后的分类选项:', options)
      } else {
        console.error('分类数据结构不符合预期', res.data)
        ElMessage.warning('获取分类数据结构异常')
      }
    } else {
      ElMessage.error(res.msg || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表出错', error)
    ElMessage.error('获取分类列表出错')
  }
}

// 查询
const handleSearch = () => {
  searchForm.pageNum = 1
  getProductList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.type = ''
  searchForm.status = ''
  handleSearch()
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新增产品'
  dialogVisible.value = true
}

// 查看详情
const handleView = async (row) => {
  try {
    // 先显示骨架屏或加载状态
    detailVisible.value = true
    detailLoading.value = true
    
    // 初始化基本数据
    productDetail.value = {
      id: row.id,
      name: row.name,
      type: row.type,
      categoryId: row.categoryId,
      categoryName: row.categoryName,
      status: row.status,
      interestRate: row.interestRate,
      loanAmount: row.loanAmount || null,
      loanTerm: row.loanTerm || null,
      createTime: row.createTime,
      updateTime: row.updateTime || row.createTime
    }
    
    // 然后获取完整数据
    const res = await productApi.getDetail(row.id)
    console.log('产品详情接口返回:', res) // 调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 处理可能的嵌套数据结构 - 增加嵌套层数检查
      let detailData = null
      
      // 第一层：直接是对象
      if (res.data && typeof res.data === 'object' && !res.data.data) {
        detailData = res.data
      }
      // 第二层：res.data.data 是对象
      else if (res.data && res.data.data && typeof res.data.data === 'object' && !res.data.data.data) {
        detailData = res.data.data
      }
      // 第三层：res.data.data.data 是对象（针对提供的返回结构）
      else if (res.data && res.data.data && res.data.data.data && typeof res.data.data.data === 'object') {
        detailData = res.data.data.data
      }
      // 新的嵌套结构：res.data 包含 code、msg 和 data，data 中再包含对象
      else if (res.data && res.data.code && res.data.data && typeof res.data.data === 'object') {
        detailData = res.data.data
      }
      else {
        console.warn('产品详情数据结构与预期不符', res.data)
        ElMessage.warning('获取产品详情格式异常')
        return
      }
      
      console.log('提取后的详情数据:', detailData) // 调试日志
      
      // 更新详情数据
      productDetail.value = detailData
    } else {
      ElMessage.error(res.msg || '获取产品详情失败')
    }
  } catch (error) {
    console.error('获取产品详情出错', error)
    ElMessage.error('获取产品详情出错')
  } finally {
    detailLoading.value = false
  }
}

// 编辑
const handleEdit = async (row) => {
  try {
    // 先显示对话框并填充基本数据
    resetForm()
    dialogTitle.value = '编辑产品'
    dialogVisible.value = true
    
    // 设置基本字段
    Object.assign(formData, {
      id: row.id,
      name: row.name,
      type: row.type,
      categoryId: row.categoryId,
      interestRate: row.interestRate,
      loanAmount: row.loanAmount || { min: 1, max: 50 },
      loanTerm: row.loanTerm || { min: 3, max: 36 },
      repaymentMethod: row.repaymentMethod || 'equal_principal_interest',
      status: row.status
    })
    
    // 然后获取完整数据
    const res = await productApi.getDetail(row.id)
    console.log('编辑产品接口返回:', res) // 调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 处理可能的嵌套数据结构 - 增加嵌套层数检查
      let productData = null
      
      // 第一层：直接是对象
      if (res.data && typeof res.data === 'object' && !res.data.data) {
        productData = res.data
      }
      // 第二层：res.data.data 是对象
      else if (res.data && res.data.data && typeof res.data.data === 'object' && !res.data.data.data) {
        productData = res.data.data
      }
      // 第三层：res.data.data.data 是对象（针对提供的返回结构）
      else if (res.data && res.data.data && res.data.data.data && typeof res.data.data.data === 'object') {
        productData = res.data.data.data
      }
      // 新的嵌套结构：res.data 包含 code、msg 和 data，data 中再包含对象
      else if (res.data && res.data.code && res.data.data && typeof res.data.data === 'object') {
        productData = res.data.data
      }
      else {
        console.warn('编辑产品数据结构与预期不符', res.data)
        ElMessage.warning('获取产品信息格式异常')
        return
      }
      
      console.log('提取后的产品数据:', productData) // 调试日志
      
      // 更新完整数据，保留已设置的ID
      const id = formData.id
      Object.assign(formData, productData)
      formData.id = id
    } else {
      ElMessage.error(res.msg || '获取产品详情失败')
    }
  } catch (error) {
    console.error('获取产品详情出错', error)
    ElMessage.error('获取产品详情出错')
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除产品"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await productApi.deleteProduct(row.id)
      if (res.code === 200 || res.code === '200') {
        ElMessage.success('删除成功')
        getProductList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除产品出错', error)
      ElMessage.error('删除产品出错')
    }
  }).catch(() => {})
}

// 更改状态
const handleChangeStatus = (row) => {
  const newStatus = row.status === 'active' ? 'inactive' : 'active'
  const statusText = newStatus === 'active' ? '上架' : '下架'
  
  ElMessageBox.confirm(`确定要${statusText}产品"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await productApi.updateStatus({
        id: row.id,
        status: newStatus
      })
      if (res.code === 200 || res.code === '200') {
        ElMessage.success(`${statusText}成功`)
        getProductList()
      } else {
        ElMessage.error(res.msg || `${statusText}失败`)
      }
    } catch (error) {
      console.error(`${statusText}产品出错`, error)
      ElMessage.error(`${statusText}产品出错`)
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      submitLoading.value = true
      try {
        const api = formData.id ? productApi.updateProduct : productApi.addProduct
        const res = await api(formData)
        console.log('提交产品表单返回:', res) // 调试日志
        
        if (res.code === 200 || res.code === '200') {
          ElMessage.success(formData.id ? '修改成功' : '新增成功')
          dialogVisible.value = false
          getProductList()
        } else {
          ElMessage.error(res.msg || (formData.id ? '修改失败' : '新增失败'))
        }
      } catch (error) {
        console.error(formData.id ? '修改产品出错' : '新增产品出错', error)
        ElMessage.error(formData.id ? '修改产品出错' : '新增产品出错')
      } finally {
        submitLoading.value = false
      }
    } else {
      console.log('表单校验失败', fields)
    }
  })
}

// 添加产品特性
const addFeature = () => {
  formData.features.push({
    key: '',
    name: '',
    value: ''
  })
}

// 删除产品特性
const removeFeature = (index) => {
  formData.features.splice(index, 1)
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: undefined,
    name: '',
    type: '',
    categoryId: undefined,
    interestRate: 4.35,
    loanAmount: {
      min: 1,
      max: 50
    },
    loanTerm: {
      min: 3,
      max: 36
    },
    repaymentMethod: 'equal_principal_interest',
    applyCondition: '',
    requiredMaterials: '',
    description: '',
    features: []
  })
}

// 分页
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  getProductList()
}

const handleCurrentChange = (val) => {
  searchForm.pageNum = val
  getProductList()
}

// 初始化
onMounted(() => {
  getProductList()
  getCategoryList()
})
</script>

<style scoped>
.product-list {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.text-center {
  text-align: center;
  line-height: 32px;
}

.text-gray-500 {
  color: #909399;
}

.mb-2 {
  margin-bottom: 8px;
}

.mt-4 {
  margin-top: 16px;
}

.font-bold {
  font-weight: bold;
}
</style> 